import { reactive } from 'vue';
import { FormItemValidate, FormRules } from '@/utils/types';

export interface LoginForm {
  username: string;
  password: string;
}

export interface UseLoginForm {
  loginForm: LoginForm;
  loginRules: FormRules;
}

export const useLoginForm = (): UseLoginForm => {
  const loginForm = reactive({
    username: 'admin',
    password: '123456',
  }) as LoginForm;

  const validateUsername: FormItemValidate = (rule, value, callback) => {
    if (value.trim().length === 0) {
      callback(new Error('请输入正确的用户名'));
    } else {
      callback();
    }
  };
  const validatePassword: FormItemValidate = (rule, value, callback) => {
    if (value.length < 6) {
      callback(new Error('密码长度不能小于6位!'));
    } else {
      callback();
    }
  };

  const loginRules = reactive({
    username: [{ required: true, trigger: 'blur', validator: validateUsername }],
    password: [{ required: true, trigger: 'blur', validator: validatePassword }],
  }) as FormRules;

  return {
    loginForm,
    loginRules,
  };
};
